﻿Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace UI
    'Public Class Print

    '    Public Shared Function FNum(ByVal d As Integer) As String

    '        Return "###,##0." & StrDup(d, "0")

    '    End Function
    '    Public Shared Function FNumS(ByVal d As Integer) As String

    '        Return "+###,##0." & StrDup(d, "0") & ";-###,##0." & StrDup(d, "0")

    '    End Function

    '    Public Shared Function NumF(ByVal n As Object, ByVal d As Integer, ByVal s As Boolean) As String

    '        If s Then
    '            Return NumS(n, d)
    '        Else
    '            Return Num(n, d)

    '        End If

    '    End Function
    '    Public Shared Function Num(ByVal n As Object, ByVal d As Integer) As String

    '        If n Is DBNull.Value Then
    '            Return "-"
    '        End If

    '        Return Format(n, "###,##0." & StrDup(d, "0"))

    '    End Function
    '    Public Shared Function NumNull(ByVal n As Object, ByVal d As Integer, IfNull As String) As String

    '        If n Is DBNull.Value Then
    '            Return IfNull
    '        End If

    '        Return Format(n, "###,##0." & StrDup(d, "0"))

    '    End Function
    '    Public Shared Function NumNullZero(ByVal n As Object, ByVal d As Integer, IfNull As String, IfZero As String) As String

    '        If n Is DBNull.Value Then
    '            Return IfNull
    '        End If

    '        If n = 0 Or Double.IsNaN(n) Then
    '            Return IfZero
    '        End If

    '        Return Format(n, "###,##0." & StrDup(d, "0"))

    '    End Function

    '    Public Shared Function Num0(ByVal n As Object) As String

    '        If n Is DBNull.Value Then
    '            Return "-"
    '        End If
    '        If Double.IsInfinity(n) Then
    '            Return "-"
    '        End If

    '        Return Format(n, "###,##0")

    '    End Function
    '    Public Shared Function Num1(ByVal n As Object) As String

    '        If n Is DBNull.Value Then
    '            Return "-"
    '        End If
    '        If Double.IsInfinity(n) Then
    '            Return "-"
    '        End If
    '        Return Format(n, "###,##0.0")

    '    End Function
    '    Public Shared Function Num2(ByVal n As Object) As String

    '        If n Is DBNull.Value Then
    '            Return "-"
    '        End If
    '        If Double.IsInfinity(n) Then
    '            Return "-"
    '        End If
    '        Return Format(n, "###,##0.00")

    '    End Function
    '    Public Shared Function Num3(ByVal n As Object) As String

    '        If n Is DBNull.Value Then
    '            Return "-"
    '        End If
    '        If Double.IsInfinity(n) Then
    '            Return "-"
    '        End If
    '        Return Format(n, "###,##0.000")

    '    End Function

    '    Public Shared Function NumS(ByVal n As Object, ByVal d As Integer) As String

    '        If n Is DBNull.Value Then
    '            Return "-"
    '        End If
    '        If Double.IsInfinity(n) Then
    '            Return "-"
    '        End If
    '        'Return n.ToString("+###,##0." & StrDup(d, "0") & ";-###,##0." & StrDup(d, "0"))
    '        Return Format(n, "+###,##0." & StrDup(d, "0") & ";-###,##0." & StrDup(d, "0"))

    '    End Function
    '    Public Shared Function Num0S(ByVal n As Object) As String

    '        If n Is DBNull.Value Then
    '            Return "-"
    '        End If
    '        If Double.IsInfinity(n) Then
    '            Return "-"
    '        End If
    '        Return Format(n, "+###,##0;-###,##0")

    '    End Function
    '    Public Shared Function Num1S(ByVal n As Object) As String

    '        If n Is DBNull.Value Then
    '            Return "-"
    '        End If
    '        If Double.IsInfinity(n) Then
    '            Return "-"
    '        End If
    '        Return NumS(n, 1)

    '    End Function
    '    Public Shared Function Num2s(ByVal n As Object) As String

    '        If n Is DBNull.Value Then
    '            Return "-"
    '        End If
    '        If Double.IsInfinity(n) Then
    '            Return "-"
    '        End If
    '        Return NumS(n, 2)

    '    End Function

    '    Public Shared Function NumCol2F(ByVal n As Object, ByVal c As Boolean) As Drawing.Color

    '        If c Then
    '            Return NumCol2(n)
    '        Else
    '            Return Nothing
    '        End If

    '    End Function

    '    Public Shared Function NumCol2(ByVal n As Object) As Drawing.Color

    '        If n Is DBNull.Value Then
    '            Return Nothing
    '        End If
    '        If Double.IsInfinity(n) Then
    '            Return Nothing
    '        End If

    '        If n >= 0 Then
    '            Return Drawing.Color.Green
    '        Else
    '            Return Drawing.Color.Red
    '        End If

    '    End Function
    '    Public Shared Function NumCol3(ByVal n As Object) As Drawing.Color

    '        If n = 0 Then
    '            Return Drawing.Color.Blue
    '        ElseIf n > 0 Then
    '            Return Drawing.Color.Green
    '        Else
    '            Return Drawing.Color.Red
    '        End If

    '    End Function
    '    Public Shared Function NumCol3(ByVal n As Object, ByVal ParamArray c() As Drawing.Color) As Drawing.Color

    '        If n > 0 Then
    '            Return c(1)
    '        Else
    '            Return c(0)
    '        End If

    '        If c.Length > 2 Then
    '            If n = 0 Then
    '                Return c(2)
    '            End If
    '        End If

    '    End Function

    '    Public Shared Function NumStr(ByVal value As Object) As String

    '        'Return value.ToString(New Globalization.CultureInfo("en-US"))
    '        Return value.ToString.Replace(",", ".")

    '    End Function

    'End Class

    Public Class Print

        Public Shared Function IsNum(n As Object) As Boolean

            If n Is DBNull.Value Then
                Return False
            End If
            If Double.IsInfinity(n) Or Double.IsNaN(n) Then
                Return False
            End If

            Return True

        End Function
        Public Shared Function FNum(ByVal d As Integer) As String

            Return "###,##0." & StrDup(d, "0")

        End Function
        Public Shared Function FNumS(ByVal d As Integer) As String

            Return "+###,##0." & StrDup(d, "0") & ";-###,##0." & StrDup(d, "0")

        End Function

        Public Shared Function NumF(ByVal n As Object, ByVal d As Integer, ByVal s As Boolean) As String

            If s Then
                Return NumS(n, d)
            Else
                Return Num(n, d)

            End If

        End Function
        Public Shared Function Num(ByVal n As Object, ByVal d As Integer) As String

            If Not IsNum(n) Then
                Return "-"
            End If

            Return Format(n, "###,##0." & StrDup(d, "0"))

        End Function
        Public Shared Function NumNull(ByVal n As Object, ByVal d As Integer, IfNull As String) As String

            If Not IsNum(n) Then
                Return IfNull
            End If

            Return Format(n, "###,##0." & StrDup(d, "0"))

        End Function
        Public Shared Function NumNullZero(ByVal n As Object, ByVal d As Integer, IfNull As String, IfZero As String) As String

            If Not IsNum(n) Then
                Return IfNull
            End If

            If n = 0 Then
                Return IfZero
            End If

            Return Format(n, "###,##0." & StrDup(d, "0"))

        End Function

        Public Shared Function Num0(ByVal n As Object) As String

            If Not IsNum(n) Then
                Return "-"
            End If

            Return Format(n, "###,##0")

        End Function
        Public Shared Function Num1(ByVal n As Object) As String

            If Not IsNum(n) Then
                Return "-"
            End If

            Return Format(n, "###,##0.0")

        End Function
        Public Shared Function Num2(ByVal n As Object) As String

            If Not IsNum(n) Then
                Return "-"
            End If

            Return Format(n, "###,##0.00")

        End Function
        Public Shared Function Num3(ByVal n As Object) As String

            If Not IsNum(n) Then
                Return "-"
            End If

            Return Format(n, "###,##0.000")

        End Function

        Public Shared Function NumS(ByVal n As Object, ByVal d As Integer) As String

            If Not IsNum(n) Then
                Return "-"
            End If
            'Return n.ToString("+###,##0." & StrDup(d, "0") & ";-###,##0." & StrDup(d, "0"))
            Return Format(n, "+###,##0." & StrDup(d, "0") & ";-###,##0." & StrDup(d, "0"))

        End Function
        Public Shared Function Num0S(ByVal n As Object) As String

            If Not IsNum(n) Then
                Return "-"
            End If

            Return Format(n, "+###,##0;-###,##0")

        End Function
        Public Shared Function Num1S(ByVal n As Object) As String

            Return NumS(n, 1)

        End Function
        Public Shared Function Num2s(ByVal n As Object) As String

            Return NumS(n, 2)

        End Function

        Public Shared Function NumCol2F(ByVal n As Object, ByVal c As Boolean) As Drawing.Color

            If c Then
                Return NumCol2(n)
            Else
                Return Nothing
            End If

        End Function

        Public Shared Function NumCol2(ByVal n As Object) As Drawing.Color

            If Not IsNum(n) Then
                Return Nothing
            End If

            If n >= 0 Then
                Return Drawing.Color.Green
            Else
                Return Drawing.Color.Red
            End If

        End Function
        Public Shared Function NumCol3(ByVal n As Object) As Drawing.Color

            If n = 0 Then
                Return Drawing.Color.Blue
            ElseIf n > 0 Then
                Return Drawing.Color.Green
            Else
                Return Drawing.Color.Red
            End If

        End Function
        Public Shared Function NumCol3(ByVal n As Object, ByVal ParamArray c() As Drawing.Color) As Drawing.Color

            If n > 0 Then
                Return c(1)
            Else
                Return c(0)
            End If

            If c.Length > 2 Then
                If n = 0 Then
                    Return c(2)
                End If
            End If

        End Function

        Public Shared Function NumStr(ByVal value As Object) As String

            'Return value.ToString(New Globalization.CultureInfo("en-US"))
            Return value.ToString.Replace(",", ".")

        End Function

    End Class
    Public Class Route

        Public CurrPage As Web.UI.Page
        Public RouteName As String

        Public Sub New()

        End Sub
        Public Sub New(ByVal P As Web.UI.Page)
            Me.CurrPage = P
            Me.RouteName = GetData("RouteName")

        End Sub

        Public Function GetValue(ByVal key As String) As String

            Return Utils.GetValue(CurrPage.RouteData.Values, key)

        End Function
        Public Function GetValueInt(ByVal key As String) As Integer

            Return Utils.GetValueInt(CurrPage.RouteData.Values, key)

        End Function
        Public Function GetValueDbl(ByVal key As String) As Double

            Return Utils.GetValueDbl(CurrPage.RouteData.Values, key)

        End Function
        Public Function GetData(ByVal key As String) As String
            Dim CurrRoute As Web.Routing.Route = CurrPage.RouteData.Route

            If CurrRoute Is Nothing Then
                Return ""
            Else
                Return Utils.GetValue(CurrRoute.DataTokens, key)
            End If

        End Function
        Public Function GetDataInt(ByVal key As String) As Integer
            Dim CurrRoute As Web.Routing.Route = CurrPage.RouteData.Route

            If CurrRoute Is Nothing Then
                Return 0
            Else
                Return Utils.GetValueInt(CurrRoute.DataTokens, key)
            End If


        End Function
        Public Function GetDataDbl(ByVal key As String) As Double
            Dim CurrRoute As Web.Routing.Route = CurrPage.RouteData.Route

            If CurrRoute Is Nothing Then
                Return 0
            Else
                Return Utils.GetValueDbl(CurrRoute.DataTokens, key)
            End If


        End Function


        'Public Shared Function MakeUrl(Reset As Boolean, ByVal r As String, ByVal d As Object) As String

        '    Dim parameters As New Web.Routing.RouteValueDictionary(d)

        '    Dim ParKeys = parameters.Keys
        '    For ct As Integer = 0 To ParKeys.Count - 1
        '        parameters(ParKeys(ct)) = StrToUrl(parameters(ParKeys(ct)))
        '    Next

        '    Dim ReqCont = Nothing
        '    If Not Reset Then
        '        ReqCont = HttpContext.Current.Request.RequestContext
        '    End If

        '    Dim vpd As Web.Routing.VirtualPathData = Web.Routing.RouteTable.Routes.GetVirtualPath(ReqCont, r.ToUpper, parameters)

        '    Return (vpd.VirtualPath)


        'End Function

        'Public Shared Function MakeUrl(ByVal r As String, ByVal d As Object) As String

        '    Return MakeUrl(False, r, d)


        'End Function


        Public Shared Function MakeUrl(InheritsParams As Boolean, ByVal r As String, ByVal d As Object) As String

            Dim parameters As New Web.Routing.RouteValueDictionary(d)

            Dim ParKeys = parameters.Keys
            For ct As Integer = 0 To ParKeys.Count - 1
                parameters(ParKeys(ct)) = StrToUrl(parameters(ParKeys(ct)))
            Next

            'Dim ReqCont As Web.Routing.RequestContext = Nothing
            If InheritsParams Then

                Dim ReqCont = HttpContext.Current.Request.RequestContext

                Dim url = DirectCast(Web.Routing.RouteTable.Routes(r), Web.Routing.Route).Url

                For Each p In ReqCont.RouteData.Values

                    If Not parameters.ContainsKey(p.Key) And url.IndexOf("{" & p.Key & "}") <> -1 Then
                        parameters.Add(p.Key, p.Value)
                    End If
                Next
            End If

            Dim vpd As Web.Routing.VirtualPathData = Web.Routing.RouteTable.Routes.GetVirtualPath(Nothing, r.ToUpper, parameters)

            Return (vpd.VirtualPath)


        End Function

        Public Shared Function MakeUrl(ByVal r As String, ByVal d As Object) As String

            Return MakeUrl(False, r, d)


        End Function
        Public Shared Function StrToUrl(ByVal s As String) As String

            Return Text.RegularExpressions.Regex.Replace(s, "[^a-z,0-9]", "-", Text.RegularExpressions.RegexOptions.IgnoreCase).ToLower

        End Function

    End Class

    Public Class Page
        Public Shared Function GetValue(ByVal key As String) As String
            Return Utils.GetValue(System.Web.HttpContext.Current.Request, key)
        End Function
        Public Shared Function GetValueInt(ByVal key As String) As Integer
            Return Utils.GetValueInt(System.Web.HttpContext.Current.Request, key)
        End Function
        Public Shared Function GetValueDbl(ByVal key As String) As Double
            Return Utils.GetValueDbl(System.Web.HttpContext.Current.Request, key)
        End Function
        Public Shared Sub RedirectTopJS(url As String)

            HttpContext.Current.Response.Write("<script>top.location.href='" + url + "';</script>")
            HttpContext.Current.Response.End()

        End Sub
        Public Shared Sub WriteLog(l As String)

            Dim c = HttpContext.Current

            If c IsNot Nothing Then

                SyncLock c

                    If c.Response.IsClientConnected And Not c.Response.BufferOutput Then
                        'r.BufferOutput = False
                        c.Response.Write(Now.ToString & " - " & l & "<br>")
                    End If

                End SyncLock

            End If


        End Sub

        Public Shared Sub ReturnStatusCode(Code As Integer)

            HttpContext.Current.Response.StatusCode = Code
            HttpContext.Current.Response.End()


        End Sub



    End Class

    Public Class GroupButton(Of tres As {IButtonControl, WebControl})

        Public Property CacheState As Object
        Public Property group As String
        Public Property cssactive As String


        Private Buttons As New List(Of tres)
        Private p As System.Web.UI.Page

        Public ReadOnly Property SelectValue() As String
            Get
                Return Me.SelectButton.CommandArgument
            End Get
        End Property

        Public Property SelectButtonID() As String
            Get
                Return Me.CacheState("_GROUP_" & Me.group)
            End Get
            Set(ByVal value As String)
                Me.CacheState("_GROUP_" & Me.group) = value
            End Set
        End Property

        Public Property SelectButton() As tres
            Get
                Return (From b In Me.Buttons Where b.ID = Me.SelectButtonID).FirstOrDefault
            End Get
            Set(value As tres)
                Me.SelectButtonID = value.ID

                SetDataButtonList()

            End Set
        End Property

        Public Event Selected(value As String)


        Sub New(cache As Object, group As String, cssactive As String)


            Me.p = HttpContext.Current.CurrentHandler
            Me.CacheState = cache
            Me.group = group
            Me.cssactive = cssactive

            Buttons = UI.Controls.FindCommandControls(Of tres)(Me.p.Controls, group)

            For Each b In Buttons
                AddHandler b.Click, AddressOf BntExport_Click
            Next
            SetDataButtonList()

        End Sub

        Private Sub SetDataButtonList()

            For Each b In Buttons
                UI.Controls.ClassSet(b, b.ID = Me.SelectButtonID, cssactive, "")
            Next

        End Sub


        Protected Sub BntExport_Click(sender As Object, e As EventArgs)

            Me.SelectButton = sender
            RaiseEvent Selected(Me.SelectValue)

        End Sub

    End Class


    Public Class Controls

        Public Shared Sub ClassAdd(ByVal o As WebControl, css As String)

            ClassRemove(o, css)
            o.CssClass = o.CssClass & " " & css


        End Sub
        Public Shared Sub ClassRemove(ByVal o As WebControl, css As String)

            o.CssClass = String.Join(" ", o.CssClass.Split({" "c}, StringSplitOptions.RemoveEmptyEntries).Where(Function(c) c <> css).ToArray)

        End Sub
        Public Shared Sub ClassReplace(ByVal o As WebControl, css As String, newcss As String)
            ClassRemove(o, css)
            ClassAdd(o, newcss)

        End Sub


        Public Shared Sub ClassSet(ByVal o As WebControl, cond As Boolean, truecss As String, falsecss As String)

            If cond Then
                ClassRemove(o, falsecss)
                ClassAdd(o, truecss)

            Else
                ClassRemove(o, truecss)
                ClassAdd(o, falsecss)
            End If

        End Sub
        'Public Shared Sub ClassSetReplace(ByVal o As WebControl, cond As Boolean, truecss As String, falsecss As String)

        '    If cond Then
        '        ClassRemove(o, falsecss)
        '        ClassAdd(o, truecss)

        '    Else
        '        ClassRemove(o, truecss)
        '        ClassAdd(o, falsecss)
        '    End If

        'End Sub
        Public Shared Function GetHiddenValue(hid As HiddenField) As String

            If hid Is Nothing Then
                Return ""
            Else
                Return hid.Value
            End If

        End Function

        Public Shared Function GetIndexData(ByVal r As Control)

            Dim i As IDataItemContainer = r
            Return i.DataItemIndex

        End Function


        Public Shared Sub ObjToControls(ByVal o As Object, ByVal c As Web.UI.Control)

            Dim t = o.GetType
            Dim Prop As Reflection.PropertyInfo
            Dim PropName = ""

            For Each Control As Web.UI.Control In c.Controls
                If Control.ID IsNot Nothing Then

                    If (Control.ID.Substring(0, 3).ToUpper = "DB_") Then
                        PropName = Control.ID.Split("_")(1)
                        Prop = t.GetProperty(PropName, Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.IgnoreCase)
                        If Prop IsNot Nothing Then

                            Select Case Control.GetType
                                Case GetType(Web.UI.WebControls.TextBox)
                                    DirectCast(Control, Web.UI.WebControls.TextBox).Text = Prop.GetValue(o, Nothing)
                                Case GetType(Web.UI.WebControls.Label)
                                    DirectCast(Control, Web.UI.WebControls.Label).Text = Prop.GetValue(o, Nothing)
                            End Select
                            'If Control.GetType = GetType(Web.UI.WebControls.TextBox) Or Control.GetType Is GetType(Web.UI.WebControls.Label) Then
                            '    DirectCast(Control, Web.UI.WebControls.TextBox).Text = Prop.GetValue(o, Nothing)
                            '    'Control.text()
                            'End If

                        End If
                        'Prop.SetValue(Nothing, "30", Nothing)

                    End If

                End If

            Next

        End Sub
        Public Shared Sub ControlsToObj(ByVal c As Web.UI.Control, ByVal o As Object)

            Dim t = o.GetType
            Dim PropItems, Prop As Reflection.PropertyInfo
            Dim PropName = ""


            PropItems = t.GetProperty("Item", New Type() {GetType(String)})

            For Each Control As Web.UI.Control In c.Controls
                If Control.ID IsNot Nothing Then

                    If (Control.ID.Substring(0, 3).ToUpper = "DB_") Then
                        PropName = Control.ID.Split("_")(1)

                        If PropItems Is Nothing Then
                            Prop = t.GetProperty(PropName, Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.IgnoreCase)
                        Else
                            Prop = PropItems
                        End If

                        If Prop IsNot Nothing Then

                            If Control.GetType Is GetType(Web.UI.WebControls.TextBox) Then
                                If PropItems Is Nothing Then
                                    Prop.SetValue(o, DirectCast(Control, Web.UI.WebControls.TextBox).Text, Nothing)
                                Else
                                    Prop.SetValue(o, DirectCast(Control, Web.UI.WebControls.TextBox).Text, New Object() {PropName})
                                End If

                                'Control.text()
                            End If

                        End If
                        'Prop.SetValue(Nothing, "30", Nothing)

                    End If

                End If

            Next


            '"OBJ_"
        End Sub
        Public Shared Function CloneControl(ByVal control As Object) As Object
            Dim type As Type = control.GetType()
            Dim properties As Reflection.PropertyInfo() = type.GetProperties()
            Dim retObject As Object = type.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, Nothing, control, Nothing)
            For Each p As Reflection.PropertyInfo In properties
                If p.CanWrite Then
                    p.SetValue(retObject, p.GetValue(control, Nothing), Nothing)
                End If
            Next
            Return retObject
        End Function
        Public Shared Function FindControl_old(Of TResult As Control)(ByVal controlID As String, ByVal controls As ControlCollection) As TResult

            For Each Control As Control In controls
                If Control.ID IsNot Nothing Then
                    If controlID.StartsWith("^") Then
                        If (Control.ID.ToUpper.StartsWith(controlID.ToUpper.Trim("^"))) Then Return Control
                    Else
                        If (Control.ID.ToUpper = controlID.ToUpper) Then Return Control

                    End If

                End If

                If Control.HasControls() Then
                    Dim nestedControl As Control = FindControl(Of TResult)(controlID, Control)
                    If Not nestedControl Is Nothing Then Return nestedControl
                End If

            Next

            Return Nothing
        End Function


        'Public Shared Function FindControl(ByVal controlID As String) As Control

        '    Return FindControl(Of Control)(controlID)

        'End Function

        'Public Shared Function FindControl(Of TResult As Control)(ByVal controlID As String) As TResult

        '    Return FindControl(Of TResult)(controlID, HttpContext.Current.CurrentHandler)

        'End Function

        'Public Shared Function FindControl(ByVal controlID As String, ByVal Parent As Control) As Control

        '    Return FindControl(Of Control)(controlID, Parent)

        'End Function
        Public Shared Function FindControl(Of TResult As Control)(ByVal controlID As String, ByVal Parent As Control) As TResult


            For Each Control As Control In Parent.Controls
                If Control.ID IsNot Nothing Then
                    If controlID.StartsWith("^") Then
                        If (Control.ID.ToUpper.StartsWith(controlID.ToUpper.Trim("^"))) Then Return Control
                    Else
                        If (Control.ID.ToUpper = controlID.ToUpper) Then Return Control

                    End If

                End If

                If Control.HasControls() Then
                    Dim nestedControl As Control = FindControl(Of TResult)(controlID, Control)
                    If Not nestedControl Is Nothing Then Return nestedControl
                End If

            Next

            Return Nothing
        End Function

        Public Shared Function FindControl(Of TResult As Control)(ByVal Parent As Control) As TResult

            For Each Control As Control In Parent.Controls
                If (Control.GetType = GetType(TResult)) Then Return Control

                If Control.HasControls() Then
                    Dim nestedControl As Control = FindControl(Of TResult)(Control)
                    If Not nestedControl Is Nothing Then Return nestedControl
                End If

            Next

            Return Nothing
        End Function
        Public Shared Function FindCommandControls(Of TResult)(ByVal controls As ControlCollection, comm As String) As List(Of TResult)


            Return FindCommandControls(Of TResult)(controls, comm, Nothing)

        End Function

        Public Shared Function FindCommandControls(Of TResult)(ByVal controls As ControlCollection, comm As String, l As List(Of TResult)) As List(Of TResult)


            If l Is Nothing Then
                l = New List(Of TResult)
            End If

            For Each Control As Control In controls
                If (Control.GetType = GetType(TResult)) Then

                    Dim b As Object = Control
                    If b.CommandName = comm Then
                        l.Add(b)
                    End If
                End If

                If Control.HasControls() Then
                    FindCommandControls(Control.Controls, comm, l)
                End If

            Next

            Return l
        End Function

        Public Shared Function ToHtml(c As Control) As String
            Dim ww As New IO.StringWriter

            c.RenderControl(New HtmlTextWriter(ww))

            Return ww.ToString


        End Function

    End Class


    Public Class List
        'Public Shared Sub Bind(ByVal Ddl As DropDownList, ByVal DataSource As Object, ByVal DataTextField As String, ByVal DataValueField As String, ByVal SelectedValue As Object, reload As Boolean)
        '    Dim tmpsel = Ddl.SelectedValue

        '    Ddl.DataSource = DataSource
        '    Ddl.DataTextField = DataTextField
        '    Ddl.DataValueField = DataValueField
        '    Ddl.DataBind()
        '    '            Try
        '    If reload Then
        '        Ddl.SelectedValue = SelectedValue
        '    Else
        '        If tmpsel.ToString <> "" Then
        '            Ddl.SelectedValue = tmpsel
        '        Else
        '            Ddl.SelectedValue = SelectedValue
        '        End If

        '    End If

        '    If DdlThematic.Items.FindByValue(tmpselThem) IsNot Nothing Then

        '    End If


        '    'Catch ex As Exception

        '    'End Try

        'End Sub
        Public Shared Sub Bind(ByVal Ddl As ListControl, ByVal DataSource As Object, ByVal DataTextField As String, ByVal DataValueField As String, ByVal SelectedValue As Object, reload As Boolean)

            Dim tmpsel As Object

            If SelectedValue.GetType.GetInterface("IList") Is Nothing Then
                tmpsel = Ddl.SelectedValue
            Else
                tmpsel = GetSelectValues(Ddl)
            End If

            Ddl.DataSource = DataSource
            Ddl.DataTextField = DataTextField
            Ddl.DataValueField = DataValueField
            Ddl.DataBind()

            If SelectedValue.GetType.GetInterface("IList") Is Nothing Then
                If reload Then
                    tmpsel = SelectedValue
                Else
                    If tmpsel.ToString = "" Then
                        tmpsel = SelectedValue
                    End If
                End If

                UI.List.SetValue(Ddl, tmpsel)

            Else
                Dim SelStr As New List(Of String)
                For ct = 0 To SelectedValue.count - 1
                    SelStr.Add(SelectedValue(ct).ToString)
                Next

                If reload Then
                    tmpsel = SelStr
                Else
                    If tmpsel.Count = 0 Then
                        tmpsel = SelStr
                    End If
                End If

                UI.List.SetSelectValues(Ddl, tmpsel)


            End If



        End Sub

        Public Shared Sub SetValue(ByVal Ddl As ListControl, Value As String)

            If Ddl.Items.FindByValue(Value) IsNot Nothing Then
                Ddl.SelectedValue = Value
            End If


        End Sub


        Public Shared Function Clone(ByRef d As ListControl, ByRef s As ListControl) As ListControl

            d.Items.Clear()
            For Each c In s.Items
                d.Items.Add(c)
            Next

            Return d


        End Function

        Public Shared Function GetSelectValuesInt(l As ListControl) As List(Of Integer)

            'Return (From i In l.GetSelectedIndices Select l.Items(i).Value).ToList

            Return (From i As ListItem In l.Items Where i.Selected Select CInt(i.Value)).ToList

        End Function
        Public Shared Function GetSelectValues(l As ListControl) As List(Of String)

            'Return (From i In l.GetSelectedIndices Select l.Items(i).Value).ToList

            Return (From i As ListItem In l.Items Where i.Selected Select i.Value).ToList

        End Function


        Public Shared Sub SetSelectValues(l As ListControl, d As List(Of Integer))
            For Each i As ListItem In l.Items
                i.Selected = d.Contains(i.Value.ToString)
            Next
        End Sub
        Public Shared Sub SetSelectValues(l As ListControl, d As List(Of String))
            For Each i As ListItem In l.Items
                i.Selected = d.Contains(i.Value.ToString)
            Next
        End Sub


    End Class
    Public Class RadioButton
        Public Shared Sub Bind(ByVal Ddl As RadioButtonList, ByVal DataSource As Object, ByVal DataTextField As String, ByVal DataValueField As String, ByVal SelectedValue As Object, reload As Boolean)
            Dim tmpsel = Ddl.SelectedValue


            Ddl.DataSource = DataSource
            Ddl.DataTextField = DataTextField
            Ddl.DataValueField = DataValueField
            Ddl.DataBind()
            Try
                If reload Then
                    Ddl.SelectedValue = SelectedValue
                Else
                    If tmpsel.ToString <> "" Then
                        Ddl.SelectedValue = tmpsel
                    Else
                        Ddl.SelectedValue = SelectedValue
                    End If

                End If

            Catch ex As Exception

            End Try

        End Sub

    End Class
    Public Class Button

        Public Shared Sub Enabled(ByRef b As Web.UI.WebControls.Button, Enabled As Boolean)

            b.CssClass = (" " & b.CssClass & " ").Replace(" button_disabled ", " ").Trim
            If Not Enabled Then
                b.CssClass &= " button_disabled"
            End If
            b.Enabled = Enabled

        End Sub

    End Class

    Public Class GridRow
        Public Shared Function GetLabel(ByVal r As GridViewRow, ByVal ID As String) As Label

            Return UI.Controls.FindControl(Of Label)(ID, r)

        End Function
        Public Shared Function GetTextBox(ByVal r As GridViewRow, ByVal ID As String) As TextBox

            Return UI.Controls.FindControl(Of TextBox)(ID, r)

        End Function
        Public Shared Function GetHiddenField(ByVal r As GridViewRow, ByVal ID As String) As HiddenField

            Return UI.Controls.FindControl(Of HiddenField)(ID, r)

        End Function
        Public Shared Function GetDropDownList(ByVal r As GridViewRow, ByVal ID As String) As DropDownList

            Return UI.Controls.FindControl(Of DropDownList)(ID, r)

        End Function
        Public Shared Function GetCheckBox(ByVal r As GridViewRow, ByVal ID As String) As CheckBox

            Return UI.Controls.FindControl(Of CheckBox)(ID, r)

        End Function
        Public Shared Function GetPanel(ByVal r As GridViewRow, ByVal ID As String) As Panel

            Return UI.Controls.FindControl(Of Panel)(ID, r)

        End Function
        Public Shared Function GetButton(ByVal r As GridViewRow, ByVal ID As String) As Web.UI.WebControls.Button

            Return UI.Controls.FindControl(Of Web.UI.WebControls.Button)(ID, r)

        End Function
        Public Shared Function GetLinkButton(ByVal r As GridViewRow, ByVal ID As String) As Web.UI.WebControls.LinkButton

            Return UI.Controls.FindControl(Of Web.UI.WebControls.LinkButton)(ID, r)

        End Function
        Public Shared Function GetImageButton(ByVal r As GridViewRow, ByVal ID As String) As Web.UI.WebControls.ImageButton

            Return UI.Controls.FindControl(Of Web.UI.WebControls.ImageButton)(ID, r)

        End Function

        Public Shared Function GetControl(Of TResult As Control)(ByVal r As GridViewRow, ByVal ID As String) As TResult

            Return UI.Controls.FindControl(Of TResult)(ID, r)

        End Function

        Public Shared Function GetIndexData(ByVal r As GridViewRow)

            Return r.DataItemIndex

        End Function
        Public Shared Function GetRow(control As Object) As GridViewRow

            Return control.dataitemContainer

        End Function
    End Class
    Public Class RepeaterRow


        Public Shared Function GetControl(Of TResult As Control)(ByVal r As RepeaterItem, ByVal ID As String) As TResult

            Return UI.Controls.FindControl(Of TResult)(ID, r)

        End Function

        Public Shared Function GetRow(control As Object) As RepeaterItem

            Return control.dataitemContainer

        End Function
    End Class

    Public Class Grid

        Public Shared Function Bind(ByRef g As GridView, ds As Object) As Object
            Return Bind(g, ds, {})

        End Function

        'Public Shared Function Bind(Of tres)(ByRef g As GridView, ds As Object, DataKeyNames() As String) As List(Of tres)
        '    Bind(g, ds, DataKeyNames)

        '    Return GetDataList(Of tres)(g)

        'End Function
        Public Shared Function Bind(ByRef g As GridView, ds As Object, DataKeyNames() As String) As Object

            If DataKeyNames.Length > 0 Then
                g.DataKeyNames = DataKeyNames
            End If
            g.DataSource = ds
            g.DataBind()

            If Not g.AllowPaging Then

                If g.HeaderRow IsNot Nothing Then
                    g.HeaderRow.TableSection = TableRowSection.TableHeader
                End If

                If g.FooterRow IsNot Nothing Then
                    g.FooterRow.TableSection = TableRowSection.TableFooter
                End If

            End If

            Return g.DataSource

        End Function
        Public Shared Function Clone(ByRef d As GridView, ByRef s As GridView) As Web.UI.WebControls.GridView

            For Each c As Web.UI.WebControls.DataControlField In s.Columns.CloneFields
                d.Columns.Add(c)
            Next
            d.DataSource = s.DataSource

            '        d.CssClass = s.CssClass
            '        d.GridLines = s.GridLines
            '        d.BorderStyle = s.BorderStyle
            '        d.BorderColor = s.BorderColor

            Return d


        End Function
        Public Shared Function GetRowsList(ByRef g As GridView) As List(Of Control)

            Return (From gr As Control In g.Rows).ToList

        End Function

        Public Shared Function GetIndexData(ByRef g As GridView, r As Integer)

            If g.Rows.Count > 0 Then
                Return g.Rows(r).DataItemIndex
            Else
                Return 0
            End If


        End Function
        Public Shared Function GetKey(ByVal g As GridView, control As Object) As Object

            Dim dr = UI.GridRow.GetRow(control)
            If dr Is Nothing Then
                Return Nothing
            End If

            If dr.RowIndex = -1 Then
                Return Nothing
            Else
                Return g.DataKeys(dr.RowIndex).Value

            End If

        End Function
        Public Shared Sub Reset(ByRef g As GridView)

            g.SelectedIndex = -1
            g.EditIndex = -1
            g.PageIndex = 0

        End Sub

        Public Shared Function GetLabel(ByVal g As GridView, ByVal r As Integer, ByVal ID As String) As Label

            Return UI.Controls.FindControl(Of Label)(ID, g.Rows(r))

        End Function
        Public Shared Function GetTextBox(ByVal g As GridView, ByVal r As Integer, ByVal ID As String) As TextBox

            Return UI.Controls.FindControl(Of TextBox)(ID, g.Rows(r))

        End Function
        Public Shared Function GetDropDownList(ByVal g As GridView, ByVal r As Integer, ByVal ID As String) As DropDownList

            Return UI.Controls.FindControl(Of DropDownList)(ID, g.Rows(r))

        End Function
        Public Shared Function GetCheckBox(ByVal g As GridView, ByVal r As Integer, ByVal ID As String) As CheckBox

            Return UI.Controls.FindControl(Of CheckBox)(ID, g.Rows(r))

        End Function

        Public Shared Function GetControl(Of TResult As Control)(ByVal g As GridView, ByVal r As Integer, ByVal ID As String) As TResult

            Return UI.Controls.FindControl(Of TResult)(ID, g.Rows(r))

        End Function

        Public Shared Function GetControl(Of TResult As Control)(ByVal g As GridView, ByVal r As Integer) As TResult


            Return UI.Controls.FindControl(Of TResult)(g.Rows(r))

        End Function
        Public Shared Function GetControl(Of TResult As Control)(ByVal g As GridView, ByVal ID As String) As TResult

            Return UI.Controls.FindControl(Of TResult)(ID, g.Rows(g.Rows.Count - 1))

            'Return g.Rows(g.Rows.Count - 1).FindControl(ID)

        End Function

        Public Shared Sub RowStyle(ByVal g As GridView, ByVal r As Integer, ByVal Name As String, Section As TableRowSection)

            g.Rows(r).TableSection = Section
            g.Rows(r).CssClass = Name

        End Sub
        Public Shared Sub RowStyle(ByVal g As GridView, ByVal r As Integer, ByVal Name As String)

            RowStyle(g, r, Name, TableRowSection.TableBody)

        End Sub
        Public Shared Sub RowStyle(ByVal g As GridView, ByVal r() As Integer, ByVal Name As String)

            For ct As Integer = 0 To r.Length - 1
                RowStyle(g, r(ct), Name)
            Next

        End Sub
        Public Shared Sub RowStyle(ByVal g As GridView, ByVal Name As String, Section As TableRowSection)

            RowStyle(g, g.Rows.Count - 1, Name, Section)

        End Sub
        Public Shared Sub RowStyle(ByVal g As GridView, ByVal Name As String)

            RowStyle(g, g.Rows.Count - 1, Name, TableRowSection.TableBody)

        End Sub
        Public Shared Sub ColStyle(ByVal g As GridView, ByVal c As Integer, ByVal Name As String)

            g.Columns(c).ItemStyle.CssClass = Name

        End Sub
        Public Shared Sub CellStyle(ByVal g As GridView, r() As Integer, c() As Integer, ByVal Name As String)

            If c.Length = 0 Then
                ReDim c(g.Columns.Count - 1)
                For ct = 0 To g.Columns.Count - 1
                    c(ct) = ct
                Next
            End If
            If r.Length = 0 Then
                ReDim r(g.Rows.Count - 1)
                For ct = 0 To g.Rows.Count - 1
                    r(ct) = ct
                Next
            End If

            For ctr As Integer = 0 To r.Length - 1
                For ctc As Integer = 0 To c.Length - 1
                    g.Rows(r(ctr)).Cells(c(ctc)).CssClass = Name
                Next
            Next

        End Sub

        'Public Shared Sub AddRow(ByVal g As GridView, r As Integer, Css As String, ByVal ParamArray p() As Object)
        '    Dim h As New GridViewRow(r, 0, ListItemType.Item, DataControlRowState.Normal)
        '    Dim c As TableCell
        '    Dim prop() As String

        '    If r = 0 Then
        '        g.HeaderRow.TableSection = TableRowSection.TableBody
        '    End If

        '    If Css <> "" Then
        '        h.CssClass = Css
        '    End If
        '    For ct As Integer = 0 To p.Count - 1
        '        If p(ct).GetType = GetType(String) Then
        '            prop = p(ct).ToString.Split(";")
        '            c = New TableCell With {.Text = prop(0)}
        '            If prop.Length > 1 Then
        '                c.Attributes("colspan") = prop(1)
        '                If prop.Length > 2 Then
        '                    c.HorizontalAlign = prop(2)
        '                    If prop.Length > 3 Then
        '                        c.Attributes("rowspan") = prop(3)

        '                        'Dim h2 = g.HeaderRow  ' As New GridViewRow(r, 0, ListItemType.Item, DataControlRowState.Normal)
        '                        'c.Text = h2.Cells(ct).Text
        '                        'h2.Cells.RemoveAt(ct)

        '                        If prop.Length > 4 Then
        '                            c.VerticalAlign = prop(4)
        '                        End If

        '                    End If
        '                End If
        '            End If

        '        Else
        '            c = p(ct)
        '        End If
        '        h.Cells.Add(c)
        '    Next

        '    If g.Controls.Count > 0 Then
        '        g.Controls(0).Controls.AddAt(r, h)

        '    End If

        'End Sub

        Public Shared Sub RemoveGridCells(ByVal g As GridView, r As Integer, ParamArray i() As Integer)
            Dim row As GridViewRow = g.Controls(0).Controls(r)
            Dim c = row.Cells

            i = i.OrderByDescending(Function(o) o).ToArray
            'Array.Sor(i)
            'If r = -1 Then
            '    c = g.HeaderRow.Cells
            'Else
            '    c = g.Rows(r).Cells
            'End If

            For ct = 0 To i.Count - 1
                c.RemoveAt(i(ct))
            Next


        End Sub

        Public Shared Sub AddGridRow(ByVal g As GridView, r As Integer, Css As String, ByVal ParamArray p() As Object)
            Dim h As New GridViewRow(r, 0, ListItemType.Item, DataControlRowState.Normal)
            Dim c As TableCell

            If r = 0 Then
                ' g.HeaderRow.TableSection = TableRowSection.TableBody
                h.TableSection = TableRowSection.TableHeader
            End If

            For ct As Integer = 0 To p.Count - 1
                If p(ct).GetType = GetType(String) Then
                    c = New TableCell
                Else
                    c = p(ct)
                End If
                h.Cells.Add(c)
            Next

            If g.Controls.Count > 0 Then
                g.Controls(0).Controls.AddAt(r, h)
            End If

            SetGridRowObj(h, Css, p)

        End Sub
        Public Shared Sub SetGridRowObj(h As GridViewRow, Css As String, ByVal ParamArray p() As Object)
            'Dim h = g.Rows(r) '  As New GridViewRow(r, 0, ListItemType.Item, DataControlRowState.Normal)
            Dim c As TableCell
            Dim prop() As String
            'Dim CellRemove As New List(Of Integer)

            If Css <> "" Then
                h.CssClass = Css
            End If
            For ct As Integer = p.Count - 1 To 0 Step -1
                c = h.Cells(ct)

                If p(ct).GetType = GetType(String) Then

                    prop = p(ct).ToString.Split(";")
                    If prop(0) <> "" Then
                        c.Text = prop(0)
                    End If
                    'c = New TableCell With {.Text = prop(0)}
                    If prop.Length > 1 Then
                        c.Attributes("colspan") = prop(1)
                        If prop.Length > 2 Then
                            c.HorizontalAlign = prop(2)
                            If prop.Length > 3 Then
                                c.Attributes("rowspan") = prop(3)
                                'CellRemove.Add(ct)
                                If prop.Length > 4 Then
                                    c.VerticalAlign = prop(4)
                                End If

                            End If
                        End If
                    End If




                    'prop = p(ct).ToString.Split(";")
                    'c = h.Cells(ct)
                    'If prop.Length > 1 Then
                    '    If prop(1) = 0 Then
                    '        h.Cells.RemoveAt(ct)
                    '    Else
                    '        c.Attributes("colspan") = prop(1)
                    '    End If
                    '    If prop.Length > 2 Then
                    '        c.HorizontalAlign = prop(2)
                    '    End If
                    'End If
                Else
                    c = p(ct)
                End If
                'h.Cells.Add(c)
            Next

            'If CellRemove.Count > 0 Then
            '    RemoveCells(h.NamingContainer, h.RowIndex + 1, CellRemove.ToArray)
            'End If

            'g.Controls(0).Controls.AddAt(r, h)

        End Sub

        Public Shared Sub SetRow(ByRef g As GridView, Css As String, ByVal ParamArray p() As Object)

            SetRow(g, g.Rows.Count - 1, Css, p)

        End Sub
        Public Shared Sub SetRow(ByVal g As GridView, r As Integer, Css As String, ByVal ParamArray p() As Object)

            SetGridRowObj(g.Rows(r), Css, p)

        End Sub
        Public Shared Sub SetHeaderRow(ByVal g As GridView, Css As String, ByVal ParamArray p() As Object)

            SetGridRowObj(g.HeaderRow, Css, p)

        End Sub

        'Public Shared Sub SetLabelRow(ByRef g As GridView, ByVal ParamArray p() As Object)

        '    SetLabelRow(g, g.Rows.Count - 1, p)

        'End Sub

        'Public Shared Sub SetLabelRow(ByRef g As GridView, ByVal r As Integer, ByVal ParamArray p() As Object)

        '    Dim gr = g.Rows(r)

        '    For ct As Integer = 0 To p.Length - 1
        '        UI.Controls.FindControl(Of Label)(gr.Cells(ct)).Text = p(ct)
        '    Next

        'End Sub

        Public Shared Sub SetLabel(ByRef g As GridView, ByVal r As Integer, ByVal Lbl As String, ByVal s As String)

            GetControl(Of Label)(g, r, Lbl).Text = s

        End Sub
        Public Shared Sub SetLabel(ByRef g As GridView, ByVal Lbl As String, ByVal s As String)

            GetControl(Of Label)(g, g.Rows.Count - 1, Lbl).Text = s

        End Sub
        'Public Shared Function GetDataList(Of tdata)(ByVal g As GridView) As List(Of tdata)

        '    Return g.DataSource

        'End Function
        'Public Shared Sub SetLabel(ByRef g As GridView, ByVal r As Integer, ByVal s As String)

        '    GetControl(Of Label)(g, r).Text = s

        'End Sub
        'Public Shared Sub SetLabel(ByRef g As GridView, ByVal s As String)

        '    GetControl(Of Label)(g, g.Rows.Count - 1).Text = s

        'End Sub
        'Public Shared Sub AddHeader(ByVal g As GridView, ByVal ParamArray p() As Object)

        '    Dim e As New Events With {.p = p.ToList}

        '    AddHandler g.RowCreated, AddressOf e.AddHeader

        'End Sub
        'Private Class Events

        '    Public p As IList(Of Object)

        '    Public Sub AddHeader(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
        '        If e.Row.RowType = DataControlRowType.Header Then
        '            Dim h As New GridViewRow(0, 0, ListItemType.Header, DataControlRowState.Normal)
        '            Dim c As TableCell
        '            Dim prop() As String

        '            For ct As Integer = 0 To Me.p.Count - 1
        '                If p(ct).GetType = GetType(String) Then
        '                    prop = p(ct).ToString.Split(";")
        '                    c = New TableCell With {.Text = prop(0)}
        '                    c.Attributes("colspan") = prop(1)
        '                    If prop.Length > 2 Then
        '                        c.HorizontalAlign = prop(2)
        '                    End If
        '                Else
        '                    c = p(ct)
        '                End If
        '                h.Cells.Add(c)
        '            Next
        '            sender.Controls(0).Controls.Add(h)

        '        End If
        '    End Sub

        'End Class
    End Class

    Public Class Rep
        Public Shared Sub Bind(ByVal rep As Repeater, ds As Object)

            rep.DataSource = ds
            rep.DataBind()

        End Sub
        Public Shared Function GetIndexData(ByVal rep As Repeater, r As Integer)

            If rep.Items.Count > 0 Then
                Return rep.Items(r).ItemIndex
            Else
                Return 0
            End If


        End Function
        Public Shared Function GetRowFromCommand(commandsource As Object) As RepeaterItem

            Return commandsource.dataitemContainer

        End Function

        Public Shared Function GetControl(Of TResult As Control)(ByVal rep As Repeater, ByVal r As Integer, ByVal ID As String) As TResult

            Return UI.Controls.FindControl(Of TResult)(ID, rep.Items(r))

        End Function

    End Class
    Public Class ListData
        Public Shared Sub Reset(ByRef g As ListView)

            g.SelectedIndex = -1
            g.EditIndex = -1

        End Sub

        Public Shared Sub Clear(ByRef g As ListView)

            Bind(g, Nothing)
            g.Items.Clear()
            Reset(g)


        End Sub
        Public Shared Function Bind(ByRef g As ListView, ds As Object) As Object

            Return Bind(g, ds, {})

        End Function
        'Public Shared Function Bind(Of tres)(ByRef g As ListView, ds As Object) As List(Of tres)

        '    Return Bind(g, ds, {})

        'End Function

        'Public Shared Function Bind(ByRef g As ListView, ds As Object, DataKeyNames() As String) As List(Of Object)
        '    Bind(g, ds, DataKeyNames)

        '    Return GetDataList(Of Object)(g)

        'End Function
        'Public Shared Function BindGetData(ByRef g As ListView, ds As Object, DataKeyNames() As String) As List(Of Object)

        '    'Public Shared Sub Bind(ByRef g As ListView, ds As Object, DataKeyNames() As String)
        '    Bind(g, ds, DataKeyNames)


        '    Return GetDataList(Of Object)(g)

        'End Function
        'Public Shared Function BindGetData(Of tres)(ByRef g As ListView, ds As Object, DataKeyNames() As String) As List(Of tres)

        '    'Public Shared Sub Bind(ByRef g As ListView, ds As Object, DataKeyNames() As String)
        '    Bind(g, ds, DataKeyNames)


        '    Return GetDataList(Of tres)(g)

        'End Function
        'Public Shared Function BindGetData2(Of tres)(ByRef g As ListView, ds As Object, DataKeyNames() As String) As List(Of tres)

        '    'Public Shared Sub Bind(ByRef g As ListView, ds As Object, DataKeyNames() As String)
        '    Bind(g, ds, DataKeyNames)


        '    Return GetDataList(Of tres)(g)

        'End Function


        Public Shared Function Bind(ByRef g As ListView, ds As Object, DataKeyNames() As String) As Object

            If DataKeyNames.Length > 0 Then
                g.DataKeyNames = DataKeyNames
            End If
            g.DataSource = ds
            g.DataBind()


            Return g.DataSource

        End Function
        'Public Shared Function Bind(Of tres)(ByRef g As ListView, ds As Object, DataKeyNames() As String) As List(Of tres)


        '    Return Bind(g, ds, DataKeyNames)

        'End Function
        Public Shared Function GetIndexData(ByVal rep As ListView, r As Integer)

            If rep.Items.Count > 0 Then
                Return rep.Items(r).DataItemIndex
            Else
                Return 0
            End If


        End Function
        'Public Shared Function GetKey(ByVal g As ListView, control As Object) As Object

        '    Dim dr = ListDataItem.GetRow(control)
        '    If dr Is Nothing Then
        '        Return Nothing
        '    End If

        '    If dr.DataItemIndex = -1 Then
        '        Return Nothing
        '    Else
        '        Return g.DataKeys(dr.DataItemIndex).Value

        '    End If

        'End Function
        'Public Shared Function GetKeys(ByVal g As ListView, control As Object) As Object

        '    Dim dr = ListDataItem.GetRow(control)
        '    If dr Is Nothing Then
        '        Return Nothing
        '    End If

        '    If dr.DataItemIndex = -1 Then
        '        Return Nothing
        '    Else
        '        Return g.DataKeys(dr.DataItemIndex).Values

        '    End If

        'End Function
        'Public Shared Function GetRow(commandsource As Object) As ListViewItem

        '    Return commandsource.dataitemContainer

        'End Function

        Public Shared Function GetControl(Of TResult As Control)(ByVal rep As ListView, ByVal r As Integer, ByVal ID As String) As TResult

            Return UI.Controls.FindControl(Of TResult)(ID, rep.Items(r))

        End Function

        Public Shared Function GetRowsList(ByRef g As ListView) As List(Of Control)

            Return (From gr As Control In g.Items).ToList

        End Function
        Public Shared Function GetDataList(Of tdata)(ByVal g As ListView) As List(Of tdata)

            Return g.DataSource

        End Function

    End Class
    Public Class ListDataItem
        Public Shared Function GetLabel(ByVal r As ListViewDataItem, ByVal ID As String) As Label

            Return UI.Controls.FindControl(Of Label)(ID, r)

        End Function
        Public Shared Function GetTextBox(ByVal r As ListViewDataItem, ByVal ID As String) As TextBox

            Return UI.Controls.FindControl(Of TextBox)(ID, r)

        End Function
        Public Shared Function GetHiddenField(ByVal r As ListViewDataItem, ByVal ID As String) As HiddenField

            Return UI.Controls.FindControl(Of HiddenField)(ID, r)

        End Function
        Public Shared Function GetDropDownList(ByVal r As ListViewDataItem, ByVal ID As String) As DropDownList

            Return UI.Controls.FindControl(Of DropDownList)(ID, r)

        End Function
        Public Shared Function GetCheckBox(ByVal r As ListViewDataItem, ByVal ID As String) As CheckBox

            Return UI.Controls.FindControl(Of CheckBox)(ID, r)

        End Function
        Public Shared Function GetPanel(ByVal r As ListViewDataItem, ByVal ID As String) As Panel

            Return UI.Controls.FindControl(Of Panel)(ID, r)

        End Function
        Public Shared Function GetButton(ByVal r As ListViewDataItem, ByVal ID As String) As Web.UI.WebControls.Button

            Return UI.Controls.FindControl(Of Web.UI.WebControls.Button)(ID, r)

        End Function
        Public Shared Function GetLinkButton(ByVal r As ListViewDataItem, ByVal ID As String) As Web.UI.WebControls.LinkButton

            Return UI.Controls.FindControl(Of Web.UI.WebControls.LinkButton)(ID, r)

        End Function
        Public Shared Function GetImageButton(ByVal r As ListViewDataItem, ByVal ID As String) As Web.UI.WebControls.ImageButton

            Return UI.Controls.FindControl(Of Web.UI.WebControls.ImageButton)(ID, r)

        End Function

        Public Shared Function GetControl(Of TResult As Control)(ByVal r As ListViewDataItem, ByVal ID As String) As TResult

            Return UI.Controls.FindControl(Of TResult)(ID, r)

        End Function

        Public Shared Function GetIndexData(ByVal r As ListViewDataItem)

            Return r.DataItemIndex

        End Function
        Public Shared Function GetData(Of tdata)(ByVal dr As ListViewDataItem) As tdata

            Return GetListView(dr).DataSource(dr.DataItemIndex)

        End Function
        Public Shared Function GetRow(control As Object) As ListViewDataItem

            Return control.dataitemContainer

        End Function
        Public Shared Function GetListView(dr As ListViewDataItem) As ListView

            Return dr.NamingContainer

        End Function

        Public Shared Function GetKey(dr As ListViewDataItem) As Object

            'Dim dr = ListDataItem.GetRow(control)
            If dr Is Nothing Then
                Return Nothing
            End If

            If dr.DataItemIndex = -1 Then
                Return Nothing
            Else
                Dim datakey = GetListView(dr).DataKeys(dr.DataItemIndex)
                If datakey.Values.Count > 1 Then
                    Return datakey.Values
                Else
                    Return datakey.Value

                End If
            End If

        End Function
        Public Shared Function GetKey(control As Object) As Object

            Return GetKey(ListDataItem.GetRow(control))


        End Function


    End Class
    'Public Class AuthUsers
    '    'Public IsAuthenticated As Boolean
    '    'Public UserData As DataRow

    '    Private UsersTable, UserDB, UsernameField, PasswordField As String
    '    Private UserConf As String

    '    Private DB As System.Data.Common.DbConnection

    '    Public Property UserData() As DataRow
    '        Get
    '            Return HttpContext.Current.Session("_" & UserConf & "_")
    '        End Get
    '        Set(ByVal value As DataRow)
    '            HttpContext.Current.Session("_" & UserConf & "_") = value
    '        End Set
    '    End Property
    '    Public ReadOnly Property IsAuthenticated() As Boolean
    '        Get
    '            Return Me.UserData IsNot Nothing
    '        End Get
    '    End Property

    '    Public Sub New()

    '        Me.New("AUTH_USERS")

    '    End Sub

    '    Public Sub New(ByVal Conf As String)
    '        Me.UserConf = Conf
    '        Me.UserDB = Utils.ConfigDictionary(UserConf)("db")
    '        Me.UsersTable = Utils.ConfigDictionary(UserConf)("table")
    '        Me.UsernameField = Utils.ConfigDictionary(UserConf)("usernamefield")
    '        Me.PasswordField = Utils.ConfigDictionary(UserConf)("passwordfield")

    '        If Me.UserData Is Nothing And HttpContext.Current.Request.Cookies(Me.UserConf & "_Username") IsNot Nothing Then
    '            Dim Username As String = HttpContext.Current.Request.Cookies(Me.UserConf & "_Username").Value
    '            Dim Password As String = HttpContext.Current.Request.Cookies(Me.UserConf & "_Password").Value
    '            Dim q = New DBase.MySql.SqlQuery(Of Object)(Me.GetDB)
    '            q.Sql("select * from " & UsersTable & " where " & Me.UsernameField & " = " & q.P(Username) & " ").ToDataTable()
    '            If q.DT.Rows.Count > 0 Then
    '                Me.UserData = q.DT.Rows(0)
    '            Else
    '                Me.UserData = Nothing
    '            End If

    '            If Me.UserData IsNot Nothing Then

    '                If Utils.MD5.MD5Compare(Me.UserData(Me.PasswordField), Password) Then
    '                    Me.LogIn(Me.UserData(Me.UsernameField), Me.UserData(Me.PasswordField), False)
    '                End If
    '            End If

    '        End If

    '    End Sub
    '    Public Function LogIn(ByVal Username As String, ByVal Password As String, ByVal SavePassword As Boolean) As Boolean
    '        Dim q = New DBase.MySql.SqlQuery(Of Object)(Me.GetDB)

    '        q.Sql("select * from " & UsersTable & " where " & Me.UsernameField & " = " & q.P(Username) & " and " & Me.PasswordField & " = " & q.P(Password)).ToDataTable()
    '        If q.DT.Rows.Count > 0 Then
    '            Me.UserData = q.DT.Rows(0)
    '        Else
    '            Me.UserData = Nothing
    '        End If

    '        If UserData IsNot Nothing Then

    '            'Me.IsAuthenticated = True

    '            If SavePassword Then
    '                HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.UserConf & "_Username", UserData(Me.UsernameField).ToString) With {.Expires = Now.AddDays(30)})
    '                HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.UserConf & "_Password", Utils.MD5.MD5Create(UserData(Me.PasswordField))) With {.Expires = Now.AddDays(30)})

    '                'HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.UserConf & "_Username", UserData(Me.UsernameField).ToString))
    '                'HttpContext.Current.Response.Cookies(Me.UserConf & "_Username").Expires = Now.AddDays(30)
    '                'HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.UserConf & "_Password", Utils.MD5.MD5Create(UserData(Me.PasswordField))))
    '                'HttpContext.Current.Response.Cookies(Me.UserConf & "_Password").Expires = Now.AddDays(30)
    '            End If
    '            Return True
    '        Else
    '            'Me.IsAuthenticated = False
    '            Return False
    '        End If


    '    End Function
    '    Public Function GetData(Of TResult As {New, Class})() As TResult
    '        Dim t = GetType(TResult)

    '        Dim PropList = DBase.Utils.GetListPropObjectDataTable(Me.UserData.Table, t)
    '        Dim obj = New TResult

    '        DBase.Utils.DataRowToObject(Me.UserData, obj, PropList)

    '        Return obj
    '        ' Return q.SqlDataObj(Of TResult)("select * from " & UsersTable & " where UserId = " & q.P(Me.UserId))

    '    End Function
    '    Private Function GetDB() As MySql.Data.MySqlClient.MySqlConnection

    '        If Me.DB Is Nothing Then
    '            Me.DB = New MySql.Data.MySqlClient.MySqlConnection( _
    '                System.Web.Configuration.WebConfigurationManager.ConnectionStrings(UserDB).ToString)
    '        End If

    '        Return Me.DB

    '        'Return New MySql.Data.MySqlClient.MySqlConnection( _
    '        '    System.Web.Configuration.WebConfigurationManager.ConnectionStrings(UserDB).ToString)

    '        'Return DirectCast(HttpContext.Current.Items(UserDB), DbLinq.Data.Linq.DataContext)

    '    End Function
    '    Public Sub LogOut()

    '        'Me.IsAuthenticated = False
    '        Me.UserData = Nothing

    '        'Dim cuser = New HttpCookie(Me.UserConf & "_Username") With {.Expires = Now.AddDays(-1)}
    '        'cuser.Expires = Now.AddDays(-1)
    '        ''cuser.Value = ""
    '        HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.UserConf & "_Username") With {.Expires = Now.AddDays(-1)})
    '        HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.UserConf & "_Password") With {.Expires = Now.AddDays(-1)})


    '        'Dim cpass = New HttpCookie(Me.UserConf & "_Password")
    '        'cpass.Expires = Now.AddDays(-1)
    '        ''cpass.Value = ""
    '        'HttpContext.Current.Response.Cookies.Add(cpass)

    '        'HttpContext.Current.Response.Cookies(Me.UserConf & "_Username").Expires = Now.AddDays(-1)
    '        'HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.UserConf & "_Password"))
    '        'HttpContext.Current.Response.Cookies(Me.UserConf & "_Password").Expires = Now.AddDays(-1)

    '        'HttpContext.Current.Request.Cookies.Remove(Me.UserConf & "_Username")
    '        'HttpContext.Current.Request.Cookies.Remove(Me.UserConf & "_Password")

    '    End Sub

    'End Class

    'Public Class AuthUsers
    '    'Public IsAuthenticated As Boolean
    '    'Public UserData As DataRow

    '    Private UsersTable, UsernameField, PasswordField As String
    '    Private UserConf As String

    '    Private DB As DBase.MySql.DBContext


    '    Public ReadOnly Property IsAuthenticated() As Boolean
    '        Get
    '            Return SessionUser <> ""
    '            'Return Me.UserData IsNot Nothing
    '        End Get
    '    End Property
    '    Private Property SessionUser() As String
    '        Get
    '            Return Utils.GetValue(HttpContext.Current.Session, "_" & UserConf & "_")
    '        End Get
    '        Set(value As String)
    '            HttpContext.Current.Session("_" & UserConf & "_") = value
    '        End Set
    '    End Property

    '    Public Sub New(DB As DBase.MySql.DBContext)

    '        Me.New("AUTH_USERS", DB)

    '    End Sub

    '    Private _MakeLogin As Boolean = False
    '    Public ReadOnly Property MakeLogin As Boolean
    '        Get
    '            Return _MakeLogin
    '        End Get
    '    End Property


    '    Public Sub New(ByVal Conf As String, DB As DBase.MySql.DBContext)
    '        Me.UserConf = Conf
    '        Me.DB = DB
    '        Dim ConfAuth = Utils.ConfigDictionary(UserConf)
    '        Me.UsersTable = ConfAuth("table")
    '        Me.UsernameField = ConfAuth("usernamefield")
    '        Me.PasswordField = ConfAuth("passwordfield")

    '        If Not Me.IsAuthenticated And HttpContext.Current.Request.Cookies(Me.UserConf & "_Username") IsNot Nothing Then
    '            Dim Username As String = HttpContext.Current.Request.Cookies(Me.UserConf & "_Username").Value
    '            Dim Password As String = HttpContext.Current.Request.Cookies(Me.UserConf & "_Password").Value
    '            Dim q = DB.GetDBQuery
    '            q.From(UsersTable).WhereAnd(Me.UsernameField, "=", Username).ToDataTable()
    '            If q.DT.Rows.Count > 0 Then
    '                If Utils.MD5.MD5Compare(q.DT.Rows(0)(Me.PasswordField), Password) Then
    '                    Me.LogIn(q.DT.Rows(0)(Me.UsernameField), q.DT.Rows(0)(Me.PasswordField), False)
    '                End If
    '            End If

    '        End If

    '    End Sub


    '    Public Function LogIn(ByVal Username As String, ByVal Password As String, ByVal SavePassword As Boolean) As Boolean
    '        Dim q = DB.GetDBQuery

    '        q.From(UsersTable).WhereAnd(Me.UsernameField, "=", Username, Me.PasswordField, "=", Password).ToDataTable()
    '        If q.DT.Rows.Count > 0 Then
    '            Me.SessionUser = q.DT.Rows(0)(Me.UsernameField)
    '            Me._MakeLogin = True
    '            If SavePassword Then
    '                HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.UserConf & "_Username", q.DT.Rows(0)(Me.UsernameField).ToString) With {.Expires = Now.AddDays(30)})
    '                HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.UserConf & "_Password", Utils.MD5.MD5Create(q.DT.Rows(0)(Me.PasswordField))) With {.Expires = Now.AddDays(30)})
    '            End If
    '            Return True
    '        Else

    '            Return False
    '        End If

    '    End Function
    '    Public Function GetData(Of TResult As {New, Class})() As TResult

    '        If Me.IsAuthenticated Then

    '            Dim ud As TResult
    '            Dim q = DB.GetDBQuery(Of TResult).NotifyChanged(True)
    '            ud = q.From(UsersTable).WhereAnd(Me.UsernameField, "=", Me.SessionUser).ToObj()
    '            Return ud
    '        Else
    '            Return Nothing
    '        End If

    '        ' Return q.SqlDataObj(Of TResult)("select * from " & UsersTable & " where UserId = " & q.P(Me.UserId))

    '    End Function
    '    'Public Function GetData(Of TResult As {New, Class})() As TResult

    '    '    If Me.IsAuthenticated Then

    '    '        Dim ud As TResult = HttpContext.Current.Items("_" & UserConf & "_")
    '    '        If ud Is Nothing Then
    '    '            Dim q = DB.GetDBQuery(Of TResult).NotifyChanged(True)
    '    '            ud = q.From(UsersTable).WhereAnd(Me.UsernameField, "=", Me.SessionUser).ToObj()
    '    '            HttpContext.Current.Items("_" & UserConf & "_") = ud
    '    '        End If
    '    '        Return ud

    '    '    Else
    '    '        Return Nothing
    '    '    End If

    '    '     Return q.SqlDataObj(Of TResult)("select * from " & UsersTable & " where UserId = " & q.P(Me.UserId))

    '    'End Function
    '    'Private Function GetDB() As MySql.Data.MySqlClient.MySqlConnection

    '    '    If Me.DB Is Nothing Then
    '    '        Me.DB = New DBase.MySql.DBContext(    New MySql.Data.MySqlClient.MySqlConnection( _
    '    '            System.Web.Configuration.WebConfigurationManager.ConnectionStrings(UserDB).ToString)
    '    '    End If

    '    '    Return Me.DB

    '    'Return New MySql.Data.MySqlClient.MySqlConnection( _
    '    '    System.Web.Configuration.WebConfigurationManager.ConnectionStrings(UserDB).ToString)

    '    'Return DirectCast(HttpContext.Current.Items(UserDB), DbLinq.Data.Linq.DataContext)

    '    'End Function
    '    Public Sub LogOut()

    '        Me.SessionUser = ""

    '        HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.UserConf & "_Username") With {.Expires = Now.AddDays(-1)})
    '        HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.UserConf & "_Password") With {.Expires = Now.AddDays(-1)})

    '    End Sub

    'End Class

    Public MustInherit Class AuthUsersBase

        Private AuthType As String

        Public ReadOnly Property IsAuthenticated() As Boolean
            Get
                Return SessionUsername <> ""
                'Return Me.UserData IsNot Nothing
            End Get
        End Property
        Protected Property SessionUsername() As String
            Get
                Return Utils.GetValue(HttpContext.Current.Session, "_" & AuthType & "_username")
            End Get
            Set(value As String)
                HttpContext.Current.Session("_" & AuthType & "_username") = value
            End Set
        End Property
        Protected Property SessionPassword() As String
            Get
                Return Utils.GetValue(HttpContext.Current.Session, "_" & AuthType & "_password")
            End Get
            Set(value As String)
                HttpContext.Current.Session("_" & AuthType & "_password") = value
            End Set
        End Property

        Public Sub New(ByVal Conf As String)
            Me.AuthType = Conf

            If Not Me.IsAuthenticated And HttpContext.Current.Request.Cookies(Me.AuthType & "_Username") IsNot Nothing Then
                Dim Username As String = HttpContext.Current.Request.Cookies(Me.AuthType & "_Username").Value
                'Dim Password As String = HttpContext.Current.Request.Cookies(Me.AuthType & "_Password").Value

                Dim UserPassword = Me.GetPassword(Username)

                If CheckPassword(UserPassword) Then
                    Me.LogIn(Username, UserPassword, False)
                End If

            End If

        End Sub
        Public Function CheckPassword(ByVal UserPassword As String) As Boolean

            Dim Check As Boolean = False
            Dim Password As String = Me.SessionPassword 'HttpContext.Current.Request.Cookies(Me.AuthType & "_Password").Value

            If Password = "" Then
                If HttpContext.Current.Request.Cookies(Me.AuthType & "_Password") IsNot Nothing Then
                    Password = HttpContext.Current.Request.Cookies(Me.AuthType & "_Password").Value
                End If
            End If

            If UserPassword <> "" Then
                If Utils.MD5.MD5Compare(UserPassword.ToUpper, Password) Then
                    Check = True
                End If
            End If

            Return Check

        End Function

        Public MustOverride Function CheckAccount(ByVal Username As String, ByVal Password As String) As Boolean
        Public MustOverride Function GetPassword(ByVal Username As String) As String
        Public MustOverride Sub OnLogin()
        Public MustOverride Function GetUserData() As Object

        Public Function LogIn(ByVal Username As String, ByVal Password As String, ByVal SavePassword As Boolean) As Boolean


            If Me.CheckAccount(Username, Password) Then
                Dim PassMd5 = Utils.MD5.MD5Create(Password.ToUpper)
                Me.SessionUsername = Username
                Me.SessionPassword = PassMd5
                If SavePassword Then
                    HttpContext.Current.Response.Cookies.Add(
                        New HttpCookie(Me.AuthType & "_Username", Username) With {
                            .Expires = Now.AddDays(30)
                        }
                    )
                    HttpContext.Current.Response.Cookies.Add(
                        New HttpCookie(Me.AuthType & "_Password", PassMd5) With {
                            .Expires = Now.AddDays(30)
                        }
                    )
                End If

                Me.OnLogin()

                Return True
            Else

                Return False
            End If

        End Function

        'Public Function GetData(Of TResult As {New, Class})() As TResult

        '    If Me.IsAuthenticated Then

        '        Dim ud As TResult = HttpContext.Current.Items("_" & UserConf & "_")
        '        If ud Is Nothing Then
        '            Dim q = DB.GetDBQuery(Of TResult).NotifyChanged(True)
        '            ud = q.From(UsersTable).WhereAnd(Me.UsernameField, "=", Me.SessionUser).ToObj()
        '            HttpContext.Current.Items("_" & UserConf & "_") = ud
        '        End If
        '        Return ud

        '    Else
        '        Return Nothing
        '    End If

        '     Return q.SqlDataObj(Of TResult)("select * from " & UsersTable & " where UserId = " & q.P(Me.UserId))

        'End Function
        'Private Function GetDB() As MySql.Data.MySqlClient.MySqlConnection

        '    If Me.DB Is Nothing Then
        '        Me.DB = New DBase.MySql.DBContext(    New MySql.Data.MySqlClient.MySqlConnection( _
        '            System.Web.Configuration.WebConfigurationManager.ConnectionStrings(UserDB).ToString)
        '    End If

        '    Return Me.DB

        'Return New MySql.Data.MySqlClient.MySqlConnection( _
        '    System.Web.Configuration.WebConfigurationManager.ConnectionStrings(UserDB).ToString)

        'Return DirectCast(HttpContext.Current.Items(UserDB), DbLinq.Data.Linq.DataContext)

        'End Function
        Public Sub LogOut()

            'Me.SessionUser = ""

            HttpContext.Current.Session.Abandon()
            HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.AuthType & "_Username") With {.Expires = Now.AddDays(-1)})
            HttpContext.Current.Response.Cookies.Add(New HttpCookie(Me.AuthType & "_Password") With {.Expires = Now.AddDays(-1)})

        End Sub

    End Class
    Public Interface IProgressable

        Event onProgressValue(Value As Integer)
        Event onProgressLog(log As String)
        Event onProgressAction(action As String)

    End Interface



    Public Class ProgressBar

        Private S As SessionState.HttpSessionState
        Private T As Long
        Public WriteTime As Boolean = False
        Public Property Value() As Integer
            Get
                If S IsNot Nothing Then
                    Return Utils.GetValueInt(S, "ProgressBar_Value")
                Else
                    Return 0
                End If

            End Get
            Set(ByVal value As Integer)
                If S IsNot Nothing Then
                    S("ProgressBar_Value") = CInt(_StartPerc + (value * (Me.PercTot / 100)))

                End If
            End Set
        End Property
        Public Property Log() As String
            Get
                If S IsNot Nothing Then
                    Return Utils.GetValue(S, "ProgressBar_Log")
                Else
                    Return 0
                End If

            End Get
            Set(value As String)
                If S IsNot Nothing Then
                    S("ProgressBar_Log") = value
                End If
            End Set
        End Property
        Public Property Action() As String
            Get
                If S IsNot Nothing Then
                    Return Utils.GetValue(S, "ProgressBar_Action")
                Else
                    Return 0
                End If

            End Get
            Set(value As String)
                If S IsNot Nothing Then
                    S("ProgressBar_Action") = value
                End If
            End Set
        End Property


        Private _StartPerc As Integer
        Public Property StartPerc() As Integer
            Get
                Return _StartPerc
            End Get
            Set(value As Integer)
                _StartPerc = value
            End Set
        End Property


        Private _PercTot As Integer
        Public Property PercTot() As Integer
            Get
                Return _PercTot
            End Get
            Set(value As Integer)
                Me._StartPerc = Me.Value
                _PercTot = value
            End Set
        End Property

        Private Sub SetValue(v As Integer)
            Me.Value = v
            If Me.WriteTime Then
                HttpContext.Current.Response.Write(((Now.Ticks - T) / 10000000).ToString & " - " & Me.Log & "<br>")
                HttpContext.Current.Response.Flush()
            End If

        End Sub
        Private Sub SetLog(l As String)
            Me.Log = l
            Me.T = Now.Ticks

        End Sub
        Private Sub SetAction(a As String)
            Me.Action = a

        End Sub

        Public Sub AddProgressObject(p As IProgressable)

            AddProgressObject(p, 100)

        End Sub
        Public Sub AddProgressObject(p As IProgressable, PercTot As Integer)

            Me.PercTot = PercTot

            InitData()

            AddHandler p.onProgressValue, AddressOf Me.SetValue
            AddHandler p.onProgressLog, AddressOf Me.SetLog
            AddHandler p.onProgressAction, AddressOf Me.SetAction

        End Sub


        Public Sub New(Session As SessionState.HttpSessionState)

            Me.S = Session


        End Sub


        Public Sub InitData()

            Me._StartPerc = 0
            Me.Value = 0
            Me.Action = ""
            Me.Log = ""

        End Sub


        Public Sub Start(Thread As Threading.ParameterizedThreadStart) ', Session As SessionState.HttpSessionState)

            Me.InitData()

            'Me.Log = "Elaborazione in corso..."
            Dim t As New Threading.Thread(Thread)

            't.CurrentThread 
            t.CurrentCulture = Threading.Thread.CurrentThread.CurrentCulture
            t.CurrentUICulture = Threading.Thread.CurrentThread.CurrentUICulture

            t.Start()

        End Sub

        Public Shared Function GetData() As ProgressBar
            Return New ProgressBar(HttpContext.Current.Session)

        End Function


    End Class

    Public Class SortControl

        Public ID As String
        Public CacheState As Object

        Private KeySortField As String
        Private KeySortType As String

        Public Property SortField() As String
            Get
                Return CacheState(Me.KeySortField)
            End Get
            Set(value As String)
                CacheState(Me.KeySortField) = value
            End Set
        End Property

        Public Property SortType() As WebControls.SortDirection
            Get
                Return CacheState(Me.KeySortType)
            End Get
            Set(value As WebControls.SortDirection)
                CacheState(Me.KeySortType) = value
            End Set
        End Property

        Public Sub New(id As String, Cache As Object)

            Me.New(id, Cache, "", SortDirection.Ascending)

        End Sub


        Public Sub New(id As String, Cache As Object, DefaultSortField As String, DefaultSortType As WebControls.SortDirection)
            Me.ID = id
            Me.CacheState = Cache

            Me.KeySortField = id & "_sort_filed"
            Me.KeySortType = id & "_sort_type"

            If CacheState(Me.KeySortField) Is Nothing Then
                CacheState(Me.KeySortField) = DefaultSortField
                CacheState(Me.KeySortType) = DefaultSortType
            End If

        End Sub

        Private Function SortTypeToSql(st As WebControls.SortDirection) As String

            If st = SortDirection.Ascending Then
                Return "ASC"
            Else
                Return "DESC"
            End If

        End Function

        Public Sub Sort(Field As String)


            If Utils.GetValue(CacheState, Me.KeySortField).ToUpper = Field.ToUpper Then
                If CacheState(Me.KeySortType) = WebControls.SortDirection.Ascending Then
                    CacheState(Me.KeySortType) = WebControls.SortDirection.Descending
                Else
                    CacheState(Me.KeySortType) = WebControls.SortDirection.Ascending
                End If
            Else
                CacheState(Me.KeySortType) = WebControls.SortDirection.Ascending
            End If

            CacheState(Me.KeySortField) = Field


        End Sub

        Public Function SortQuery(Of tResult As {New, Class})(q As DBase.MySql.SqlQuery(Of tResult)) As DBase.MySql.SqlQuery(Of tResult)

            If CacheState(Me.KeySortField) = "" Then
                Return q
            Else
                Return q.SetOrderBy(CacheState(Me.KeySortField) & " " & SortTypeToSql(CacheState(Me.KeySortType)))
            End If


        End Function

        Public Function SortList(Of tResult)(ByRef l As List(Of tResult)) As List(Of tResult)
            Dim t As Type = GetType(tResult)

            If CacheState(Me.KeySortField) Is Nothing Then
                Return l
            End If

            Dim prop = t.GetProperty(CacheState(Me.KeySortField), Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.IgnoreCase)
            Dim st As WebControls.SortDirection = CacheState(Me.KeySortType)

            If st = SortDirection.Ascending Then

                l = (From e In l Order By prop.GetValue(e, Nothing) Ascending).ToList()
            Else
                l = (From e In l Order By prop.GetValue(e, Nothing) Descending).ToList()
            End If

            Return l
        End Function


    End Class


    Namespace Validator


        Public Enum ValidatorResultType
            [Error] = 1
            [Warning] = 2
        End Enum
        Public Class ValidatorResult
            Inherits List(Of ValidatorItem)

            Public Overloads Sub Add(ErrMess As String)

                Me.Add(New UI.Validator.ValidatorItem With {.Message = ErrMess})

            End Sub
            Public Function GetByType(t As ValidatorResultType) As ValidatorResult
                Dim Vr = New ValidatorResult
                Dim Vi = From r In Me Where r.Type = t

                For Each i In Vi
                    Vr.Add(i)
                Next
                'Return Me.Where(Function(o) o.Type = t)

                Return Vr

            End Function

            Public Sub Print(c As Object)
                Me.Visible(c)

                If c.text = "" Then
                    For Each i In Me
                        If i.Message <> "" Then
                            c.Text &= i.Message & "<br>"
                        End If
                    Next
                End If

            End Sub
            Public Sub PrintList(c As Object)
                Me.Visible(c)

                c.Text = "<ul class=""ErrorDataValidateList"">"
                For Each i In Me
                    c.Text &= "<li>" & i.Message & "</li>"
                Next
                c.Text &= "</ul>"
            End Sub

            Public Sub Visible(c As Object)

                c.visible = Me.Count > 0

            End Sub


        End Class
        Public Class ValidatorItem
            Public ID As Integer
            Public Message As String
            Public Type As ValidatorResultType = ValidatorResultType.Error
            Public DataItem As New Dictionary(Of String, Object)
        End Class


        Public Interface Ivalidator

            Function Validate() As UI.Validator.ValidatorResult

        End Interface


        Public Class ValidatorGroup
            'Implements Ivalidator


            Public val As New List(Of Ivalidator)
            'Public ValidatorControl As Object
            Public Property ValidatorGlobal As New UI.Validator.ValidatorResult
            'Public Property ValidatorObj As New UI.Validator.ValidatorResult


            'Protected MustOverride Function CheckValidation() As ValidatorResult

            'Protected MustOverride Function Check() As ValidatorResult


            'Private _ValidatorUIControl As New Dictionary(Of ValidatorResultType, Object)
            'Public Property ValidatorUIControl(vt As ValidatorResultType) As Object
            '    Get
            '        If _ValidatorUIControl.ContainsKey(vt) Then
            '            Return _ValidatorUIControl(vt)
            '        Else
            '            Return Nothing
            '        End If
            '    End Get
            '    Set(value As Object)
            '        _ValidatorUIControl(vt) = value
            '    End Set
            'End Property


            Public Function ValidatorCheck() As ValidatorResult

                Dim globalresui As New ValidatorResult

                For Each v In val

                    Dim res = v.Validate
                    ValidatorGlobal.AddRange(res)
                    'If v.Control IsNot Nothing Then
                    '    res.GetByType(ValidatorResultType.Error).Print(v.Control)
                    'Else
                    '    globalresui.AddRange(res)
                    'End If

                Next

                'globalresui.GetByType(ValidatorResultType.Error).Print(Me.ValidatorUIControl(ValidatorResultType.Error))
                'globalresui.GetByType(ValidatorResultType.Warning).Print(Me.ValidatorUIControl(ValidatorResultType.Warning))
                'Me.PrintValidator()

                Return ValidatorGlobal

            End Function


            'Public Sub PrintValidator()

            '    PrintValidatorType(ValidatorGlobal, ValidatorResultType.Error)
            '    PrintValidatorType(ValidatorGlobal, ValidatorResultType.Warning)

            'End Sub

            'Private Sub PrintValidatorType(ValRes As ValidatorResult, contr As Object)

            '    If contr IsNot Nothing Then
            '        'contr.cssclass = "ValidatorResult_" & Vt.ToString
            '        ValRes.Print(contr)
            '    End If

            'End Sub
            'Private Sub PrintValidatorType2(ValRes As ValidatorResult, Vt As ValidatorResultType)

            '    If Me.ValidatorUIControl(Vt) IsNot Nothing Then
            '        Me.ValidatorUIControl(Vt).cssclass = "ValidatorResult_" & Vt.ToString
            '        ValRes.GetByType(Vt).Print(Me.ValidatorUIControl(Vt))
            '    End If

            'End Sub


        End Class

        Public Class ValidatorUI
            Implements Ivalidator

            Public Property Validator As Ivalidator
            Public Property Control As Control

            Public ValidatorBool As Func(Of Boolean)
            Public ValidatorRes As Func(Of UI.Validator.ValidatorResult)

            Public ActionControl As Action

            Public Sub New(ValidatorRes As Func(Of UI.Validator.ValidatorResult))
                Me.ValidatorRes = ValidatorRes
            End Sub
            Public Sub New(ValidatorBool As Func(Of Boolean))
                Me.ValidatorBool = ValidatorBool
            End Sub

            Public Sub New(Validator As Ivalidator, Control As Control)

                Me.Validator = Validator
                Me.Control = Control

            End Sub
            Public Sub New(Validator As Ivalidator, ActionControl As Action)

                Me.Validator = Validator
                Me.ActionControl = ActionControl

            End Sub


            'Public Function Validate() As ValidatorResult Implements Ivalidator.Validate

            '    If Me.ffboo IsNot Nothing Then
            '        Dim ValRes As New UI.Validator.ValidatorResult
            '        If Me.ffboo() Then
            '            ValRes.Add("ERR")
            '        End If
            '        Return ValRes
            '    Else
            '        Return Me.ff()
            '    End If
            '    'RaiseEvent CustomValidate(ValRes)

            '    'Return ValRes

            'End Function

            Public Sub New(Validator As Ivalidator)

                Me.Validator = Validator

            End Sub

            Public Function Validate() As ValidatorResult Implements Ivalidator.Validate

                Dim ValRes As UI.Validator.ValidatorResult

                If Me.ValidatorBool IsNot Nothing Then
                    ValRes = New UI.Validator.ValidatorResult
                    If Me.ValidatorBool() Then
                        ValRes.Add("ERR")
                    End If
                    Return ValRes
                ElseIf Me.ValidatorRes IsNot Nothing Then

                    ValRes = Me.ValidatorRes()
                Else

                    ValRes = Me.Validator.Validate

                End If


                If Me.Control IsNot Nothing Then
                    ValRes.Print(Me.Control)
                End If

                If Me.ActionControl IsNot Nothing Then
                    Me.ActionControl()
                End If

                Return ValRes
            End Function


        End Class
        Public Class UIValidators

            Public Shared Function Required(testc As TextBox, ui As Control) As Ivalidator

                Dim v As New ValidatorUI(
                    Function()
                        ui.Visible = testc.Text = ""
                        Return testc.Text = ""
                    End Function
                )

                Return v

            End Function

            Public Shared Function Equal(test1 As TextBox, test2 As TextBox, ui As Control) As Ivalidator

                Dim v As New ValidatorUI(
                    Function()
                        ui.Visible = test1.Text <> test2.Text
                        Return test1.Text <> test2.Text
                    End Function
                )

                Return v

            End Function

        End Class
        Public Class DataValidator

            Public Shared Function Email(value As String) As Boolean

                Dim pattern = "^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"
                Dim match = Text.RegularExpressions.Regex.Match(value.ToString.Trim, pattern, Text.RegularExpressions.RegexOptions.IgnoreCase)

                Return match.Success

            End Function

            '            Dim pattern = "^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"
            '            Dim match = Text.RegularExpressions.Regex.Match(Value.ToString.Trim, pattern, Text.RegularExpressions.RegexOptions.IgnoreCase)


        End Class

        'Public MustInherit Class ValidatorBase(Of tres)
        '    'Implements Ivalidator



        '    'Public ValidatorControl As Object
        '    Public Property ValidatorGlobal As UI.Validator.ValidatorResult
        '    Public Property ValidatorObj As New UI.Validator.ValidatorResult


        '    Protected MustOverride Function CheckValidation() As ValidatorResult

        '    'Protected MustOverride Function Check() As ValidatorResult


        '    Private _ValidatorUIControl As New Dictionary(Of ValidatorResultType, Object)
        '    Public Property ValidatorUIControl(vt As ValidatorResultType) As Object
        '        Get
        '            If _ValidatorUIControl.ContainsKey(vt) Then
        '                Return _ValidatorUIControl(vt)
        '            Else
        '                Return Nothing
        '            End If
        '        End Get
        '        Set(value As Object)
        '            _ValidatorUIControl(vt) = value
        '        End Set
        '    End Property

        '    Property ObjToValidate As tres
        '    Public Sub New()

        '    End Sub
        '    Protected Sub New(o As tres)

        '        Me.ObjToValidate = o

        '    End Sub

        '    Public Function ValidatorCheck() As ValidatorResult

        '        ValidatorObj = Me.CheckValidation()

        '        'Dim ValRes = ValidatorClass


        '        If ValidatorGlobal Is Nothing Then
        '            ValidatorGlobal = ValidatorObj
        '        Else
        '            ValidatorGlobal.AddRange(ValidatorObj)
        '        End If

        '        Me.PrintValidator()

        '        Return ValidatorObj

        '    End Function

        '    'Public Function Validate() As ValidatorResult Implements Ivalidator.Validate

        '    '    Return Me.CheckValidation

        '    'End Function



        '    Public Sub PrintValidator()

        '        PrintValidatorType(ValidatorGlobal, ValidatorResultType.Error)
        '        PrintValidatorType(ValidatorGlobal, ValidatorResultType.Warning)

        '    End Sub

        '    Private Sub PrintValidatorType(ValRes As ValidatorResult, Vt As ValidatorResultType)

        '        If Me.ValidatorUIControl(Vt) IsNot Nothing Then
        '            Me.ValidatorUIControl(Vt).cssclass = "ValidatorResult_" & Vt.ToString
        '            ValRes.GetByType(Vt).Print(Me.ValidatorUIControl(Vt))
        '        End If

        '    End Sub

        'End Class

        'Namespace Validators
        '    Public Class RequiredValidator
        '        Implements Ivalidator

        '        Public Message As String
        '        Public Value As String

        '        Public Sub New(value As String)
        '            Me.Value = value
        '        End Sub


        '        Public Function Validate() As ValidatorResult Implements Ivalidator.Validate
        '            Dim ValRes As New UI.Validator.ValidatorResult

        '            If Me.Value.ToString.Trim = "" Then
        '                ValRes.Add(Me.Message)
        '            End If

        '            Return ValRes

        '        End Function

        '    End Class
        '    Public Class RequiredValidatorui
        '        Implements Ivalidator

        '        Private testc As TextBox
        '        Private ui As Control

        '        Public Sub New(testc As TextBox, ui As Control)
        '            Me.testc = testc
        '            Me.ui = ui

        '        End Sub

        '        Public Function Validate() As ValidatorResult Implements Ivalidator.Validate
        '            Dim ValRes As New UI.Validator.ValidatorResult

        '            If Me.testc.Text.Trim = "" Then
        '                ValRes.Add(Me.Message)
        '            End If

        '            Return ValRes

        '        End Function

        '    End Class
        '    'Public Class CustomValidator
        '    '    Implements Ivalidator

        '    '    Public Message As String

        '    '    Public Event CustomValidate(val As UI.Validator.ValidatorResult)

        '    '    Public ffboo As Func(Of Boolean)
        '    '    Public ff As Func(Of UI.Validator.ValidatorResult)

        '    '    Public Sub New(ff As Func(Of UI.Validator.ValidatorResult))
        '    '        Me.ff = ff
        '    '    End Sub
        '    '    Public Sub New(ffboo As Func(Of Boolean))
        '    '        Me.ffboo = ffboo
        '    '    End Sub

        '    '    Public Function Validate() As ValidatorResult Implements Ivalidator.Validate

        '    '        If Me.ffboo IsNot Nothing Then
        '    '            Dim ValRes As New UI.Validator.ValidatorResult
        '    '            If Me.ffboo() Then
        '    '                ValRes.Add("ERR")
        '    '            End If
        '    '            Return ValRes
        '    '        Else
        '    '            Return Me.ff()
        '    '        End If
        '    '        'RaiseEvent CustomValidate(ValRes)

        '    '        'Return ValRes

        '    '    End Function

        '    'End Class
        '    Public Class EmailValidator
        '        Implements Ivalidator

        '        'Public Data As Object
        '        Public Message As String
        '        Public Value As String

        '        Public Function Validate() As ValidatorResult Implements Ivalidator.Validate
        '            Dim ValRes As New UI.Validator.ValidatorResult

        '            Dim pattern = "^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"
        '            Dim match = Text.RegularExpressions.Regex.Match(Value.ToString.Trim, pattern, Text.RegularExpressions.RegexOptions.IgnoreCase)

        '            If Not match.Success Then
        '                ValRes.Add(Me.Message)
        '            End If

        '            Return ValRes

        '        End Function
        '    End Class
        '    Public Class RequiredValidatorList
        '        Implements Ivalidator


        '        'Public Data As Object
        '        Public DataList As IList
        '        Public Value As String

        '        Public Function Validate() As ValidatorResult Implements Ivalidator.Validate
        '            Dim ValRes As New UI.Validator.ValidatorResult

        '            Dim Find = False
        '            For Each l In DataList
        '                If l.ToString = Value.ToString Then
        '                    Find = True
        '                    Exit For
        '                End If
        '            Next

        '            If Not Find Then
        '                ValRes.Add("Dato non Valido")
        '            End If

        '            Return ValRes
        '        End Function
        '    End Class

        'End Namespace
        'Public Class Validators

        '    Public Shared Function Required2(vui As Validator.ValidatorsUI, control As Control, Data As String) As UI.Validator.ValidatorResult
        '        If vui Is Nothing Then vui = New Validator.ValidatorsUI
        '        vui.val.Add(New UI.Validator.ValidatorUIItem With {.Validator = New UI.Validator.RequiredValidator With {.str = Data}, .Control = control})

        '        Return vui.ValidatorCheck

        '    End Function
        '    Public Shared Function Required(ByRef GlobalValidator As UI.Validator.ValidatorResult, control As Control, Data As Object) As UI.Validator.ValidatorResult
        '        Dim Validator = New UI.Validator.RequiredValidator(Data) With {.ValidatorGlobal = GlobalValidator}

        '        If control IsNot Nothing Then
        '            Validator.ValidatorUIControl(ValidatorResultType.Error) = control
        '        End If

        '        Return Validator.ValidatorCheck

        '    End Function

        '    Public Shared Function RequiredList(ByRef GlobalValidator As UI.Validator.ValidatorResult, control As Control, Data As Object, DataList As IList) As UI.Validator.ValidatorResult
        '        Dim Validator = New UI.Validator.RequiredValidatorList With {
        '            .ObjToValidate = Data, .DataList = DataList, .ValidatorGlobal = GlobalValidator}

        '        If control IsNot Nothing Then
        '            Validator.ValidatorUIControl(ValidatorResultType.Error) = control
        '        End If

        '        Return Validator.ValidatorCheck

        '    End Function

        'End Class

    End Namespace

End Namespace

